package com.cn.springcloudwechat.controller.base;

import com.cn.springcloudwechat.common.ajax.AjaxRes;
import com.cn.springcloudwechat.common.mybatis.Page;
import com.cn.springcloudwechat.common.utils.base.Const;
import com.cn.springcloudwechat.common.utils.base.UuidUtil;
import com.cn.springcloudwechat.common.utils.webpage.PageData;
import com.cn.springcloudwechat.model.security.AccountShiroUtil;
import com.cn.springcloudwechat.model.system.account.Account;
import com.cn.springcloudwechat.model.system.resources.Resources;
import com.cn.springcloudwechat.service.system.resources.ResourcesService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class BaseController<T> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    public String AJAX_FAIL = "error:falure!";
    public String AJAX_SUCCESS = "success";
    @Autowired
    ResourcesService resourcesService;

    /**
     * 返回数据
     */
    AjaxRes ajaxRes = getAjaxRes();

    /**
     * 得到PageData
     */
    public PageData getPageData() {
        return new PageData(this.getRequest());
    }

    /**
     * 得到ModelAndView
     */
    public ModelAndView getModelAndView() {
        return new ModelAndView();
    }

    public AjaxRes getAjaxRes() {
        return new AjaxRes();
    }

    /**
     * 得到request对象
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 得到图片上传项目路径
     *
     * @return
     */
    public static String getRealPath() {
        return getRequest().getServletContext().getRealPath("/uploadImage");
    }

    /**
     * 得到response
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        return ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 得到32位的uuid
     *
     * @return
     */
    public String get32UUID() {
        return UuidUtil.get32UUID();
    }

    /**
     * 得到分页列表的信息
     *
     * @param <T>
     */
    @SuppressWarnings("hiding")
    public <T> Page<T> getPage() {
        return new Page<T>();
    }

    public static void logBefore(Logger logger, String interfaceName) {
        logger.info("");
        logger.info("start");
        logger.info(interfaceName);
    }

    public static void logAfter(Logger logger) {
        logger.info("end");
        logger.info("");
    }

    /**
     * 资源的权限（显示级别）
     *
     * @param type 资源类别
     * @return
     */
    public List<Resources> getPermitBtn(String type) {
        List<Resources> perBtns = new ArrayList<Resources>();
        try {
            String menu = getPageData().getString("menu");
            if (StringUtils.isNotBlank(menu)) {
                String menuNum = menu.replaceAll("menu", "");
                String userId = AccountShiroUtil.getCurrentUser().getAccountId();
                perBtns = resourcesService.findBtn(type, menuNum, userId);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return perBtns;
    }

    /**
     * 资源的权限（URl级别）
     *
     * @param type 资源类别(优化速度)
     * @return
     */
    protected boolean doSecurityIntercept(String type) {
        try {
            String servletPath = getRequest().getServletPath();
            servletPath = StringUtils.substringBeforeLast(servletPath, ".");// 去掉后面的后缀
            String userId = AccountShiroUtil.getCurrentUser().getAccountId();
            List<Resources> authorized = resourcesService.resAuthorized(userId, type);
            for (Resources r : authorized) {
                if (r != null && StringUtils.isNotBlank(r.getResUrl())) {
                    if (StringUtils.equals(r.getResUrl(), servletPath)) {
                        return true;
                    }
                }

            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return false;
    }

    /**
     * 资源的权限（URl级别,拥有第一级资源权限，这资源才能访问）
     *
     * @param type 资源类别(优化速度)
     * @param url  第一级资源
     * @return
     */
    protected boolean doSecurityIntercept(String type, String url) {
        try {
            String userId = AccountShiroUtil.getCurrentUser().getAccountId();
            List<Resources> authorized = resourcesService.resAuthorized(userId, type);
            for (Resources r : authorized) {
                if (r != null && StringUtils.isNotBlank(r.getResUrl())) {
                    if (StringUtils.equals(r.getResUrl(), url)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return false;
    }

    /**
     * 判断操作是否成功
     */
    public AjaxRes isAjaxOperation(int col, String param) {
        if (col == 0) {
            ajaxRes.setFailMsg(AJAX_FAIL);
        } else {
            ajaxRes.setSucceed(param, AJAX_SUCCESS);
        }
        logger.info(ajaxRes.toJSONString());
        return ajaxRes;
    }

    public AjaxRes isAjaxOperation(List<Map<String, String>> list) {
        if (org.springframework.util.StringUtils.isEmpty(list)) {
            ajaxRes.setFailMsg(AJAX_FAIL);
        } else {
            ajaxRes.setSucceed(list, AJAX_SUCCESS);
        }
        logger.info(ajaxRes.toJSONString());
        return ajaxRes;
    }

    public AjaxRes isAjaxOperation(Page<Object> page) {
        if (org.springframework.util.StringUtils.isEmpty(page)) {
            ajaxRes.setFailMsg(AJAX_FAIL);
        } else {
            ajaxRes.setSucceed(page, AJAX_SUCCESS);
        }
        logger.info(ajaxRes.toJSONString());
        return ajaxRes;
    }

    public AjaxRes isAjaxOperation(String str) {
        if (org.springframework.util.StringUtils.isEmpty(str)) {
            ajaxRes.setFailMsg(AJAX_FAIL);
        } else {
            ajaxRes.setSucceed(str, AJAX_SUCCESS);
        }
        logger.info(ajaxRes.toJSONString());
        return ajaxRes;
    }

    public static String romdom() {
        Random random = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            int s = random.nextInt(8) + 1;
            buffer.append(s);
        }

        return buffer.toString();

    }

    public static void getParamMap(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue()[0];
            System.err.println(key + "\t" + value);
        }
    }


    public static Map<String, Object> stringToMap(String obj, String fistSymbol, String secondSymbol) {
        Map<String, Object> map = new HashMap<>();
        //String code="code:0,msg:sueecss";
        String a[] = obj.split(fistSymbol);
        if (fistSymbol != null) {
            for (int i = 0; i < a.length; i++) {
                if (secondSymbol != null) {
                    for (int k = 0; k < a[i].split(secondSymbol).length; k++) {
                        String b[] = a[i].split(secondSymbol);
                        if (k % 2 == 0) {
                            map.put(b[k], b[k + 1]);
                        }
                    }
                }
            }
        }

        for (Entry<String, Object> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
        return map;
    }

    // 判断一个字符串是否都为数字
    public static boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    public static String getloginName() {
        System.out.println("longinName=" + (String) getRequest().getSession().getAttribute(Const.longinName));
        return (String) getRequest().getSession().getAttribute(Const.longinName);
    }

    /**
     * 获取当前后台登录用户
     * @return
     */
    public static Account getLoginSysUser(){
        Session session=SecurityUtils.getSubject().getSession();
        Account acount=(Account) session.getAttribute(Const.SESSION_USER);
        return acount;
    }
}
